PssMemory = echarts.init(document.getElementById('pss_memory'));
processCpuInfo = echarts.init(document.getElementById('cpu'));
Fps = echarts.init(document.getElementById('fps'));
$(function () {
    let localStorage = window.localStorage;
    let data = localStorage.getItem("data");
    let data_ = JSON.parse(data);
    let _data = handler_data(data_);
    fpsoption = {
        // color: '#ff197f',
        dataZoom: [
            {
                id: 'dataZoomX',
                type: 'slider',
                xAxisIndex: [0],
                filterMode: 'filter'
            }],
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'line'
            }
        },
        legend: {
            data: handler_fps_echart(_data, "（游戏）帧率")[2]
        },
        xAxis: {
            // type: 'time',//由于定义的now时间格式不是完整的时间格式（我需要用的是时分秒），也就是说我只截取了一部分，
            // 所以不能使用time类型，需要使用默认的类型才能显示出来，否则显示不出来
            splitLine: {
                show: false
            },
            data: handler_fps_echart(_data, "（游戏）帧率")[0]
        },
        yAxis: {
            name: "单位(帧)",
            type: 'value',
            boundaryGap: [0, '100%'],
            splitLine: {
                show: false
            },
        },
        series: handler_fps_echart(_data, "（游戏）帧率")[1],
    };
    pssoption = {
        // color: '#ff197f',
        dataZoom: [
            {
                id: 'dataZoomX',
                type: 'slider',
                xAxisIndex: [0],
                filterMode: 'filter'
            }],
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'line'
            }
        },
        legend: {
            data: handler_memory_data(_data, "PSS内存-main")[2]
        },
        xAxis: {
            // type: 'time',//由于定义的now时间格式不是完整的时间格式（我需要用的是时分秒），也就是说我只截取了一部分，
            // 所以不能使用time类型，需要使用默认的类型才能显示出来，否则显示不出来
            splitLine: {
                show: false
            },
            data: handler_memory_data(_data, "PSS内存-main")[0]
        },
        yAxis: {
            name: "单位(Mb)",
            type: 'value',
            boundaryGap: [0, '100%'],
            splitLine: {
                show: false
            },
        },
        series: handler_memory_data(_data, "PSS内存-main")[1]
    };
    cpuoption = {
        // color: '#ff197f',
        dataZoom: [
            {
                id: 'dataZoomX',
                type: 'slider',
                xAxisIndex: [0],
                filterMode: 'filter'
            }],
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'line'
            }
        },
        legend: {
            data: handler_cpu_data(_data, "应用进程-main")[2],
        },
        xAxis: {
            splitLine: {
                show: false
            },
            data: handler_cpu_data(_data, "应用进程-main")[0],
        },
        yAxis: {
            name: "单位(%)",
            type: 'value',
            boundaryGap: [0, '100%'],
            splitLine: {
                show: false
            }
        },
        series: handler_cpu_data(_data, "应用进程-main")[1],
    };
    pssoption && PssMemory.setOption(pssoption);
    cpuoption && processCpuInfo.setOption(cpuoption);
    fpsoption && Fps.setOption(fpsoption);

//===============按钮点击事件=============
    $("#_fps").click(function () {
        Fps.clear();
        fpsoption.legend.data = handler_fps_echart(_data, "（游戏）帧率")[2];
        fpsoption.series = handler_fps_echart(_data, "（游戏）帧率")[1];
        fpsoption && Fps.setOption(fpsoption);
    });
    $("#fps_delay").click(function () {
        Fps.clear();
        fpsoption.legend.data = handler_fps_echart(_data, "（游戏）延迟次数")[2];
        fpsoption.series = handler_fps_echart(_data, "（游戏）延迟次数")[1];
        fpsoption && Fps.setOption(fpsoption);
    });
    $("#fps_delay_time").click(function () {
        Fps.clear();
        fpsoption.legend.data = handler_fps_echart(_data, "（游戏）最长延迟时间")[2];
        fpsoption.series = handler_fps_echart(_data, "（游戏）最长延迟时间")[1];
        fpsoption && Fps.setOption(fpsoption);
    });
    $("#_mem").click(function () {
        PssMemory.clear();
        pssoption.legend.data = handler_memory_data(_data, "PSS内存-main")[2];
        pssoption.series = handler_memory_data(_data, "PSS内存-main")[1];
        pssoption && PssMemory.setOption(pssoption);
    });
    $("#_PrivateDirty_mem").click(function () {
        PssMemory.clear();
        pssoption.legend.data = handler_memory_data(_data, "PrivateDirty内存-main")[2];
        pssoption.series = handler_memory_data(_data, "PrivateDirty内存-main")[1];
        pssoption && PssMemory.setOption(pssoption);
    });
    $("#total_memory").click(function () {
        PssMemory.clear();
        pssoption.legend.data = handler_memory_data(_data, "全局占用")[2];
        pssoption.series = handler_memory_data(_data, "全局占用")[1];
        pssoption && PssMemory.setOption(pssoption);
    });
    $("#_cpu").click(function () {
        processCpuInfo.clear();
        cpuoption.legend.data = handler_cpu_data(_data, "应用进程-main")[2];
        cpuoption.series = handler_cpu_data(_data, "应用进程-main")[1];
        cpuoption && processCpuInfo.setOption(cpuoption);
    });
    $("#_total_cpu").click(function () {
        processCpuInfo.clear();
        cpuoption.legend.data = handler_cpu_data(_data, "全局占用")[2];
        cpuoption.series = handler_cpu_data(_data, "全局占用")[1];
        cpuoption && processCpuInfo.setOption(cpuoption);
    });


});

//将时间戳转化成时间
function formatDate(timestamp) {
    let date = new Date(timestamp);
    let minutes = addZero(date.getMinutes());
    let seconds = addZero(date.getSeconds());
    return minutes + ':' + seconds;
}

handler_data = function (data) {
    let legend = [];
    let series = [];
    let i = 0;
    for (let key in data) {
        legend.push(key);
        series[i] = data[key];
        i++;
    }
    let data_for_json = {"legend": legend, "series": series};
    return data_for_json;
};

handler_fps_echart = function (data, strategy) {
    let legend = data["legend"]; //取到的legend为id数组如：[15,16]
    let series = data["series"]; //取到的series为数据的数组如
    let temp_time = [];
    let _series = [];
    let _lengend = [];
    for (let i = 0; i < series.length; i++) {
        let fps_data = [];
        let fps_time = [];
        // console.log(series[i].data.CPU);
        if (typeof (series[i].data.FPS[strategy]) == "undefined") {
            fps_data.push(0);
        } else {
            for (let j = 0; j < series[i].data.FPS[strategy].length; j++) {
                let fps = Number(series[i].data.FPS[strategy][j].b.toFixed(2));
                let t = formatDate(series[i].data.FPS[strategy][j].a);
                fps_time.push(t);
                fps_data.push(fps);
            }
        }
        let _format = {
            symbol: "none",
            name: legend[i] + "_" + strategy,
            type: "line",
            data: fps_data
        };
        _lengend.push(legend[i] + "_" + strategy);
        temp_time.push.apply(temp_time, fps_time);
        _series.push(_format);
    }
    temp_time.sort();
    return {0: temp_time, 1: _series, 2: _lengend};
};
handler_memory_data = function (data, strategy) {
    let legend = data["legend"]; //取到的legend为id数组如：[15,16]
    let series = data["series"]; //取到的series为数据的数组如
    let temp_time = [];
    let _series = [];
    let _lengend = [];
    let mem_key_name, private_mem_key_name;
    //获取内存下的动态key值
    for (let i = 0; i < series.length; i++) {
        let mem_data = [];
        let mem_time = [];
        for (let key in series[i].data.Memory) {
            // "PSS内存-main"
            if (key.search(strategy) !== -1) {
                mem_key_name = key;
            }
            // "PrivateDirty内存-main"
            if (key.search(strategy) !== -1) {
                private_mem_key_name = key;
            }
        }
        if (mem_key_name.search(strategy) !== -1) {
            if (typeof (series[i].data.Memory[mem_key_name]) == "undefined") {
                mem_data.push(0);
            } else {
                for (let j = 0; j < series[i].data.Memory[mem_key_name].length; j++) {
                    let mem = Number(series[i].data.Memory[mem_key_name][j].b.toFixed(2));
                    let t = formatDate(series[i].data.Memory[mem_key_name][j].a);
                    mem_time.push(t);
                    mem_data.push(mem);
                }
            }
        }
        if (private_mem_key_name.search(strategy) !== -1) {
            if (typeof (series[i].data.Memory[private_mem_key_name]) == "undefined") {
                mem_data.push(0);
            } else {
                for (let j = 0; j < series[i].data.Memory[private_mem_key_name].length; j++) {
                    let private_mem = Number(series[i].data.Memory[private_mem_key_name][j].b.toFixed(2));
                    mem_data.push(private_mem);
                }
            }
        }
        if (strategy === "全局占用") {
            if (typeof (series[i].data.Memory[strategy]) == "undefined") {
                mem_data.push(0);
            } else {
                for (let j = 0; j < series[i].data.Memory[strategy].length; j++) {
                    let g_mem = Number(series[i].data.Memory[strategy][j].b.toFixed(2));
                    mem_data.push(g_mem);
                }
            }
        }
        // "全局占用"
        let _format = {
            symbol: "none",
            name: legend[i] + "_" + strategy,
            type: "line",
            data: mem_data
        };
        _lengend.push(legend[i] + "_" + strategy);
        temp_time.push.apply(temp_time, mem_time);
        _series.push(_format);
    }
    temp_time.sort();
    return {0: temp_time, 1: _series, 2: _lengend};
};
handler_cpu_data = function (data, strategy) {
    let legend = data["legend"]; //取到的legend为id数组如：[15,16]
    let series = data["series"]; //取到的series为数据的数组如
    let temp_time = [];
    let _series = [];
    let _lengend = [];
    let cpu_key_name;
    // 应用进程 - main - 2498
    for (let i = 0; i < series.length; i++) {
        let cpu_data = [];
        let cpu_time = [];
        for (let key in series[i].data.CPU) {
            // "PSS内存-main"
            if (key.search(strategy) !== -1) {
                cpu_key_name = key;
            }
        }
        // console.log(series[i].data.CPU[strategy]);
        if (typeof (series[i].data.CPU[strategy]) == "undefined") {
            cpu_data.push(0);
        } else {
            for (let j = 0; j < series[i].data.CPU[strategy].length; j++) {
                let cpu = Number(series[i].data.CPU[strategy][j].b.toFixed(2));
                let t = formatDate(series[i].data.CPU[strategy][j].a);
                cpu_data.push(cpu);//获取CPU值
                cpu_time.push(t);//获取时间
            }
        }
        if (cpu_key_name.search(strategy) !== -1) {
            if (typeof (series[i].data.CPU[cpu_key_name]) == "undefined") {
                cpu_data.push(0);
            } else {
                for (let j = 0; j < series[i].data.CPU[cpu_key_name].length; j++) {
                    let cpu = Number(series[i].data.CPU[cpu_key_name][j].b.toFixed(2));
                    let t = formatDate(series[i].data.CPU[cpu_key_name][j].a);
                    cpu_time.push(t);//获取时间
                    cpu_data.push(cpu);//获取线程CPU值
                }
            }
        }
        let _format = {
            symbol: "none",
            name: legend[i] + "_" + strategy,
            type: "line",
            data: cpu_data
        };
        _lengend.push(legend[i] + "_" + strategy);
        temp_time.push.apply(temp_time, cpu_time);
        _series.push(_format);
    }
    temp_time.sort();
    return {0: temp_time, 1: _series, 2: _lengend};
};

//加0处理
function addZero(num) {
    return num < 10 ? '0' + num : num;
}

//==============保存图片到服务端=====================
export_report = function () {
    //拿到图片的base64地址
    //放大2倍，一定程度上减缓压缩造成的模糊问题，背景设置为白色
    let pss_data_base64 = PssMemory.getDataURL({pixelRatio: 0.5, backgroundColor: '#fff'});
    let cpu_data_base64 = processCpuInfo.getDataURL({pixelRatio: 0.5, backgroundColor: '#fff'});
    let fps_base64 = Fps.getDataURL({pixelRatio: 0.5, backgroundColor: '#fff'});
    let arr = [];
    let email = document.getElementById('inputEmail').value;
    let input_project_name = document.getElementById('project_name').value;
    let client_version = document.getElementById('client_version').value;
    let server_version = document.getElementById('server_version').value;
    let devices = document.getElementById('devices').value;
    let environment_data = [];
    let req = /^[a-zA-Z0-9]*@37.com$/;
    if (email === "") {
        let html = document.getElementById('email');
        html.innerHTML = "<span style=\"color: red\">邮件内容不能为空</span>";
    } else {
        if (!req.test(email)) {
            let html = document.getElementById('email');
            html.innerHTML = "<span style=\"color: red\">邮件格式不正确</span>";
        } else {
            document.getElementById('email').style.display = 'none'; //如果邮件已经输入有值了，则隐藏红色提示元素
            // let
            if (pss_data_base64 !== null || cpu_data_base64 !== null || fps_base64 !== null) {
                arr.push(pss_data_base64);
                arr.push(cpu_data_base64);
                arr.push(fps_base64);
            }
            let localStorage = window.localStorage;
            let project_id = localStorage.getItem('project_id');
            let project_name = localStorage.getItem('project_name');
            if (project_id === null && project_name === null) {
                alert('无法获取项目名字或者记录id，请返回列表页面重进试试！')
            } else {
                environment_data.push(email);
                environment_data.push(input_project_name);
                environment_data.push(client_version);
                environment_data.push(server_version);
                environment_data.push(devices);
                environment_data.push(project_id);
                environment_data.push(project_name);
                let send_data = {'arr': arr, 'environment_data': environment_data};
                $.ajax({
                    type: 'post',
                    url: '/exprot_report/',
                    traditional: true,
                    data: send_data,
                    async: false,
                    success: function (data) {
                        if (data === 200) {
                            alert('报告发送成功！请留意查收邮件！');
                            $('#sendreport').modal('hide');
                        } else {
                            alert('报告发送成功！请留意查收邮件！');
                            $('#sendreport').modal('hide');
                        }
                    }
                })
            }
        }
    }
};
